package com.zyy.joseata.interceptor;


import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;

import java.sql.Connection;
import java.util.Properties;

/**
 * @author zhangyy
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class MyBatisPlusStatementInterceptor extends OptimisticLockerInnerInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取原始 StatementHandler
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();

        // 获取原始的 SQL
        BoundSql boundSql = statementHandler.getBoundSql();
        String originalSql = boundSql.getSql();
        System.out.println("execute sql: =:>" +originalSql);
        // 调用原始的 prepare 方法，此时会使用自定义的 Statement
        Object result =invocation.proceed();
        System.out.println("after executing sql statement => "+result);
        return result;
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以在这里进行初始化和配置
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }
}